package com.diver.flinkdemo.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diver.flinkdemo.Trd.fjdxy.FJDXYController;
import com.diver.flinkdemo.Trd.lnlt.LNLTController;
import com.diver.flinkdemo.Trd.tljy.TLJYController;
import com.diver.flinkdemo.Trd.yjy.YJYController;
import com.diver.flinkdemo.Trd.yzh.YiZiHuiController;
import com.diver.flinkdemo.Trd.zgyzh.ZgyzhController;
import com.diver.flinkdemo.dto.xxt.C40DataVO;
import com.diver.flinkdemo.entity.DalData;
import com.diver.flinkdemo.entity.PushData;
import com.diver.flinkdemo.entity.ResultConfig;
import com.diver.flinkdemo.entity.Trd.zgyzh.UniversalReply;
import com.diver.flinkdemo.entity.xxt.*;
import com.diver.flinkdemo.enums.MessageEnum;
import com.diver.flinkdemo.enums.StuCardTypeEnum;
import com.diver.flinkdemo.service.*;
import com.diver.flinkdemo.service.impl.*;
import com.diver.flinkdemo.utils.*;
import com.diver.flinkdemo.utils.xiaoyang.XiaoYangUrlConst;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;

import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;

/**
 * @author yangs
 */
@Slf4j

public class DalDataController extends BaseController {

//    private KafkaTemplate kafkaTemplate;

    private ILocationInfoService locationInfoService = new LocationInfoServiceImpl();

//    private SosInfoService sosInfoService;

    private IRedisService redisService = new RedisServiceImpl();

    private IStudentCardService studentCardService = new StudentCardServiceImpl();

    private IDeviceModeService deviceModeService = new DeviceModeServiceImpl();

    private ITerminalUnitService terminalUnitService = new TerminalUnitServiceImpl();
    private IMoreSettingService moreSettingService = new MoreSettingService();
    private IFenceService fenceService = new FenceServiceImpl();
    private IMessageService messageService = new MessageService();
    private IDevUploadDataService devUploadDataService = new DevUploadDataImpl();
    private ILastLocationService lastLocationService = new LastLocationServiceImpl();
    private IIssuedPermissionRecordService issuedPermissionRecordService = new IssuedPermissionRecordServiceImpl();
    private IMessageSendService messageSendService = new MessageSendServiceImpl();
    private ISmsCollectionService smsCollectionService = new SmsCollectionServiceImpl();
    private IHttpService httpService = new HttpServiceImpl();
    private ICallRecordService callRecordService = new CallRecordServiceImpl();
    private IClockSettingsService clockSettingsService = new ClockSettingsServiceImpl();
    private IPersonTerminalInfoService personTerminalInfoService = new IPersonTerminalInfoServiceImpl();
    private IPersonDepartService personDepartService = new PersonDepartServiceImpl();
    private YJYController yjyController = new YJYController();
    private TLJYController tljyController = new TLJYController();
    private LNLTController lnltController = new LNLTController();
    private FJDXYController fjdxyController = new FJDXYController();
    private YiZiHuiController yiZiHuiController = new YiZiHuiController();
    private XiaoYangDealController xiaoYangDealController = new XiaoYangDealController();
    private ZgyzhController zgyzhController = new ZgyzhController();
    private ISosInfoService sosInfoService = new SosInfoService();

    private String topic = "xxt-dal-handle";
    private String topic_yzh = "xxt-yzh-handle";
    private String topic_shbx = "xxt-shbx-handle";
    private String topic_zgyzh = "xxt-zgyzh-handle";
    private String topic_fjdxy = "xxt-dxy-handle";
    private String topic_yjy = "xxt-yjy-handle";
    private String topic_tljy = "xxt-tljy-handle";
    private String topic_lnlt = "xxt-lnlt-handle";
    private String schoolId = "";
    private String personId = "";

    C40DataVO c40DataVO = new C40DataVO();
    public PushData dalSendApp(DalData dalData) throws InvocationTargetException, IllegalAccessException {
        LocationInfo locationInfo = null;
        TerminalUnit terminalUnit = null;
        PushData pushData = new PushData();
        String imei = "";

        String personType = "1";
        try {
            log.info("dal data: {}", dalData);
            if (dalData == null) {
                log.info("dalData is null!");
                return null;
            }
            imei = dalData.getImei();
            BeanUtils.copyProperties(c40DataVO,dalData);
            if (StringUtils.isBlank(dalData.getImei())) {
                log.error("imei 为空 错误");
                return null;
            }

            String type = dalData.getTypeIdent();
            String status = dalData.getStatus();
            if ("SOS1".equals(type) || "PHL".equals(type) || "UPMODE".equals(type) || "CR".equals(type) || "MONITOR".equals(type) || "SILENCETIME1".equals(type) || "WEATHER".equals(type) || "PRIORITY".equals(type)) {
                return null;
            }
            terminalUnit = super.getOneByCardNum(dalData.getImei(),11);

            if (null == terminalUnit) {
                log.error("{} imei 不存在学生证", dalData.getImei());
                return null;
            }else {
                personId = personTerminalInfoService.getBindPersonId(terminalUnit.getCardNum());
                Depart depart = personDepartService.getBindMasterDepart(personId);
                schoolId = depart!=null ? depart.getId() : "";
            }
            //todo 推送省中台相关
            screenAccountName(terminalUnit, "szt");
            if (StuCardTypeEnum.XTC0.getType().equals(terminalUnit.getTerminalSeries())) {
                if ("CALLNOTE".equals(type)) {//通话记录
//                    saveStudentLiveness(studentCard, "thsc", "通话时长", sxlData.getCallTime());
                }
                if ("POWERON".equals(type)) {//开机
                    String key = dalData.getImei() + "_kj";
                    Long l = (Long) redisService.get(key, Long.class);
                    if(null == l){
                        //添加推送省中台信息
                    /*int i = saveStudentLiveness(studentCard, "kj", "开机", "");
                    if(i > 0){
                        redisService.set(key, DateUtil.getTomorrowZeroSeconds(), DateUtil.getTomorrowZeroSeconds());
                    }*/
                    }
                }
            }
//            if ("HEARTBEAT".equals(type)){
//                LastLocation lastLocation = new LastLocation();
//                lastLocation.setCardNum(imei);
//                lastLocation.setCurrentStatus("1");
//                lastLocationService.saveLastLocation(lastLocation);
//                //redis缓存心跳状态，缓存10分钟
//                redisService.set("heartbeat_"+imei,600L,"online");
//            }
            if("SMSMSG".equals(type)) {//消息发送上报回调
                if("0".equals(status)) {
                    this.setRemindMessage(imei, "消息发送", PropertyUtil.readValue("wReturnUrl") + "messageRecord.html?imei=" + imei, 16);
                }
                messageSendService.updateMessageStatus(c40DataVO);
                return null;
            }else if ("MSGLOG".equals(type)) {
                smsCollectionService.addSmsCollection(c40DataVO);
            }
            if("REMIND".equals(type)) {//闹钟设置上报回调
                if("0".equals(status)) {
                    this.setRemindMessage(imei, "闹钟设置", PropertyUtil.readValue("wReturnUrl") + "clockSettings.html?imei=" + imei, 16);
                }
                clockSettingsService.updateClockSettings(c40DataVO);
            }
            if("APPMAN".equals(type)) {//应用程序安装卸载回调
                if("0".equals(status)) {
                    this.setRemindMessage(imei, "应用程序设置", PropertyUtil.readValue("wReturnUrl") + "applicationManagement.html?imei=" + imei, 16);
                }
                moreSettingService.updateMoreSetting(c40DataVO);
            }
            if("WIFISCAN".equals(type)){//wifi扫描
                String wifiInfos=c40DataVO.getWifiInfos();
                List<Wifi> wifiList= JSONArray.parseArray(wifiInfos, Wifi.class);
                log.info("{}缓存附近的wifi：{}",imei,wifiInfos);
//                trajectoryClient.cacheWifiInfoAroundCard(imei,wifiList);
                redisService.set("around_"+imei+"_wifi", 300L,wifiList);
            }

            if ("CALLRECORD".equals(type)) {//通话记录
                //todo 推送省中台相关
//                saveStudentLiveness(studentCard, "thsc", "通话时长", dalData.getCallTime());
                callRecordService.addCallRecord(c40DataVO);
            }
            if ("LOGIN".equals(type)) {//开机
                log.info("学生ICCID为:{}", terminalUnit.getIccid());

                if ("XXT".equals(terminalUnit.getDistributionChannel())) {

                    if(StringUtils.isNotBlank(terminalUnit.getIccid())){ //如果iccidNew为空不去进行iccid校验

                        Depart depart = personDepartService.getDepartByTerminalId(terminalUnit.getId());

                        TerminalUnit terminal = new TerminalUnit();

                        if (1 == depart.getIsFitCard()) {  //开启了机卡不一致限制

                            if (!terminalUnit.getIccid().equals(dalData.getIccid())) {
                                //如果iccid与维护iccid不一致
                                log.info("调用模板消息发送接口！");
                                //推卡夫卡发模板消息
                                terminalUnitService.updateLimitPhoneCard(terminalUnit.getCardNum(),1);

                                //设置机卡不一致模板消息
//                                pushData.setTypeIdent("ICCID");
                                dalData.setTypeIdent("ICCID");
                                if (1 == depart.getIsEntrance()) {

                                    log.info("机卡不一致开启时,进行限制:{}", terminalUnit.getCardNum());
                                    log.info("修改学生证表中的门禁消息机卡不一致校验字段为开启", terminal.getLimitMessageByCard());
                                    terminalUnitService.updateLimitMessageByCard(terminalUnit.getCardNum(),1);

                                } else {
                                    log.info("根据学校id:{}获取校企云租户Id:{}", depart.getId(), depart.getTenantId());
                                    log.info("修改学生证限制门禁消息字段为关闭:{}", terminal.getCardNum());
                                    terminalUnitService.updateLimitMessageByCard(terminalUnit.getCardNum(),0);
                                }
                            } else {

                                terminalUnitService.updateLimitPhoneCard(terminalUnit.getCardNum(),0);

                                if (1 == terminalUnit.getLimitMessageByCard()) {

                                    log.info("机卡不一致校验通过时，去修改已经被限制的卡证");
                                    log.info("修改学生证限制门禁消息字段为关闭:{}", terminalUnit.getCardNum());
                                    terminalUnitService.updateLimitMessageByCard(terminalUnit.getCardNum(),0);
                                }
                            }
                        } else {
                            terminalUnitService.updateLimitPhoneCard(terminalUnit.getCardNum(),0);

                            log.info("机卡不一致未开启时，直接将校企云的机卡不一致限制门禁消息关闭");
                            if (1 == terminalUnit.getLimitMessageByCard()) {

                                log.info("修改学生证限制门禁消息字段为关闭:{}", terminalUnit.getCardNum());
                                terminalUnitService.updateLimitMessageByCard(terminalUnit.getCardNum(),0);
                            }
                        }
                    }else {
                        log.info("学生证IccidNew为空，不进行iccid校验:{}",terminalUnit.getCardNum());
//                        terminalUnit.setLimitByPhoneCard(0);
//                        terminalUnitService.updateById(terminalUnit);
                        terminalUnitService.updateLimitPhoneCard(terminalUnit.getCardNum(),0);
                    }
                }
                String key = terminalUnit.getCardNum() + "_kj";
                Long l = (Long) redisService.get(key, Long.class);
                if (null == l) {
                    //添加推送省中台信息
                    //todo 推送省中台相关
//                    int i = saveStudentLiveness(studentCard, "kj", "开机", "");
//                    if (i > 0) {
//                        redisService.set(key, DateUtil.getTomorrowZeroSeconds(), DateUtil.getTomorrowZeroSeconds());
//                    }
                }
                if (CommonResource.CARDVERSION_XXT.equals(terminalUnit.getDistributionChannel())) {
                    //开机下发定位模式
                    //todo 暂时注释
//                    LocationMode freq = businessClient.sendUDWhenICCID(studentCard.getImei());
                    LocationMode freq = new LocationMode();
                    if (null != freq) {//查到定位模式设置则下发
                        log.info("{}imei开机查询定位模式信息{}",terminalUnit.getCardNum(),freq.getGpsRepInterval());
                        //暂时注释
//                        businessClient.sendMode(studentCard.getImei(), studentCard.getCardType(), freq);
                    }else {
                        //定位模式被删，查询默认模式
                        DeviceMode defaultMode = deviceModeService.getDefaultMode();
                        /*LocationMode defaultFreq = new LocationMode();
                        defaultFreq.setGpsRepInterval(defaultMode.getGpsRepInterval());
                        defaultFreq.setPositionFirst(defaultMode.getPositionFirst());
                        log.info("{}imei开机查询默认定位模式信息{}",studentCard.getId(),defaultFreq.getGpsRepInterval());
                        sendMode(studentCard.getImei(), studentCard.getCardType(), defaultFreq);*/
                        moreSettingService.setModifyMode(terminalUnit.getCardNum(),defaultMode.getId(),terminalUnit.getTerminalSeries());
                    }
                }
                if (StuCardTypeEnum.XTC1.getType().equals(terminalUnit.getTerminalSeries())) {
                    //暂时注释
//                    businessClient.s etICCIDIssue(studentCard.getImei());
                }

                if("1".equals(status)) {
                    String imeiV = c40DataVO.getImei() + "-v";
                    String softwareVersion = c40DataVO.getSoftwareVersion();
                    String hardwareVersion = c40DataVO.getHardwareVersion();
                    JSONObject json = new JSONObject();
                    if(StringUtils.isNotBlank(softwareVersion) && StringUtils.isNotBlank(hardwareVersion)) {
                        json.put("softwareVersion", softwareVersion);
                        json.put("hardwareVersion", hardwareVersion);
                        redisService.set(imeiV, json);
                    }
                }
            }
            if ("GET_PHL".equals(type) || "GET_SOS1".equals(type) || "GET_SILENCETIME1".equals(type)) {
                //暂时注释
//                businessClient.sendGetICCIDIssue(studentCard.getImei(), type);
            }
            locationInfo = getLocation(locationInfo, dalData);
            log.info("接受德普设备转换后数据: {}", locationInfo);
            if (StuCardTypeEnum.XTC0.getType().equals(terminalUnit.getTerminalSeries())){
                if (CommonResource.CARDVERSION_XXT.equals(terminalUnit.getDistributionChannel()) || CommonResource.CARDVERSION_SCHJY.equals(terminalUnit.getDistributionChannel())) {
                    handleSxlXXT(type, terminalUnit, locationInfo,pushData);
                } else if (CommonResource.CARDVERSION_XYZJ.equals(terminalUnit.getDistributionChannel())) {//晓羊平台推送
                    handleSxlXYZJ(type, terminalUnit, dalData, locationInfo);
                }
            } else if (CommonResource.CARDVERSION_XXT.equals(terminalUnit.getDistributionChannel()) || CommonResource.CARDVERSION_SCHJY.equals(terminalUnit.getDistributionChannel()) || CommonResource.CARDVERSION_TLJY.equals(terminalUnit.getDistributionChannel())) {
                pushData = handleXXT(type, terminalUnit, locationInfo, pushData);
                if (StuCardTypeEnum.XTC40.getType().equals(terminalUnit.getTerminalSeries()) || StuCardTypeEnum.XTC2.getType().equals(terminalUnit.getTerminalSeries())) {
                    if ("CALLRECORD".equals(type) && null != dalData.getCallFlg() && 3 == dalData.getCallFlg() && StringUtils.isNotBlank(dalData.getCallNum())) {//通话记录模板消息
                        pushData.setCallNum(dalData.getCallNum());
                        pushData.setSendType(2);
                    }
                }
                if (null != locationInfo) {
                    String electricity = locationInfo.getElectricity();
                    pushData.setPower(electricity);
                    if (StringUtils.isNotBlank(electricity) && !"null".equals(electricity)) {
                        Integer electriitys = Integer.parseInt(electricity);
                        if (electriitys >= 40 && electriitys <= 50) {
                            String keys = locationInfo.getImei() + "_" + DateUtil.getNowDate();
                            Integer val = (Integer) redisService.get(keys, Integer.class);
                            if (null == val) {
                                String typeIdent = pushData.getTypeIdent();
                                if (pushData.getUdMsgType() != null || "AL".equals(typeIdent) || "OFFUP".equals(typeIdent) || "AL_BATTERY".equals(typeIdent)) {
                                    pushData.setSendType(3);
                                }else {
                                    pushData.setSendType(1);
                                }
                                redisService.set(keys, DateUtil.getTomorrowZeroSeconds(), electriitys);
                            }
                        }
                    }
                }
            } else if (CommonResource.CARDVERSION_XYZJ.equals(terminalUnit.getDistributionChannel())) {//晓羊平台推送
                locationInfo = handleXYZJ(type, terminalUnit, dalData, locationInfo);
            } else if (CommonResource.CARDVERSION_YZH.equals(terminalUnit.getDistributionChannel())) {//翼智慧云教平台
                locationInfo = handleYZH(type, terminalUnit, dalData, locationInfo);
            } else if (CommonResource.CARDVERSION_SHBX.equals(terminalUnit.getDistributionChannel())) {//翼智慧云教平台-上海百学
                locationInfo = handleSHBX(type, terminalUnit, dalData, locationInfo);
            } else if (CommonResource.CARDVERSION_ZGYZH.equals(terminalUnit.getDistributionChannel())) {//紫光翼智慧
                locationInfo = handleZGYZH(type, terminalUnit, dalData, locationInfo);
            } else if (CommonResource.CARDVERSION_FJDXYZS.equals(terminalUnit.getDistributionChannel())) {
                if ("UD".equals(type) || "AL".equals(type) || "AL_BATTERY".equals(type)) {
                    locationInfo = handleFJDXYZS(type, terminalUnit, dalData, locationInfo);
                }
            } else if (CommonResource.CARDVERSION_YJY.equals(terminalUnit.getDistributionChannel()) || CommonResource.CARDVERSION_LNLT.equals(terminalUnit.getDistributionChannel()) || CommonResource.CARDVERSION_TLJY.equals(terminalUnit.getDistributionChannel())) {//壹教云,聊您联通,天立教育
                locationInfo = handleYJY(type, terminalUnit, dalData, locationInfo);
            }
            return pushData;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            log.info("", e);
            log.error("", e);
            //处理逻辑出错后，保留getLocation()方法之后的locationInfo数据
        } finally {
            log.info("finally save locationInfo:{}", locationInfo);
            if (dalData!=null &&locationInfo!=null) {
                super.saveExercise(terminalUnit, locationInfo,schoolId);
//                QueryWrapper<LocationInfo> wrapper = new QueryWrapper<>();
//                wrapper.eq("msg_id",locationInfo.getMsgId());
//                wrapper.eq("imei",locationInfo.getImei());
//                LocationInfo one = locationInfoService.getByParams(wrapper);
//                if (null == one) {
//                    super.saveExercise(terminalUnit, locationInfo);
//                }
//                else {
//                    log.info("消息重复处理，l-msgId:{}",locationInfo.getMsgId());
//                }
            }
//            else if (dalData!=null && "XSZ_UP_MSG".equals(dalData.getType())) {
//                DevUploadData uploadData = new DevUploadData();
//                BeanUtils.copyProperties(dalData,uploadData);
//                QueryWrapper<DevUploadData> wrapper = new QueryWrapper<>();
//                wrapper.eq("msg_id",uploadData.getMsgId());
//                wrapper.eq("imei",uploadData.getImei());
//                if (devUploadDataService.getOne(wrapper) == null){
//                    uploadData.setCreateTime(System.currentTimeMillis());
//                    log.info("devUploadData save...");
//                    devUploadDataService.save(uploadData);
//                }else {
//                    log.info("消息重复处理，d-msgId:{}",uploadData.getMsgId());
//                }
//            }

        }
        return null;
    }

    //校芯通平台处理
    PushData handleXXT(String type, TerminalUnit terminalUnit, LocationInfo locationInfo, PushData pushData) throws Exception {
//        PushData pushData = new PushData();
        BeanUtils.copyProperties(pushData,locationInfo);
        String stuId = terminalUnit.getCardNum();
        String lat = locationInfo.getLat(), lng = locationInfo.getLon(), address = locationInfo.getAddress();
        switch (type) {
            case "HEARTBEAT"://心跳
//                if (StuCardTypeEnum.XTC40.getType().equals(terminalUnit.getTerminalSeries()) || StuCardTypeEnum.XTC2.getType().equals(terminalUnit.getTerminalSeries())) {
//                    LastLocation lastLocation = new LastLocation();
//                    lastLocation.setCardNum(locationInfo.getImei());
//                    lastLocation.setNetStatus(locationInfo.getNetStatus());
//                    lastLocation.setElectricity(locationInfo.getElectricity());
//                    lastLocation.setUploadTime(new Date(locationInfo.getUploadTime()));
//                    QueryWrapper<LastLocation> wrapper = new QueryWrapper<>();
//                    wrapper.eq("card_num",locationInfo.getImei());
//                    if (lastLocationService.getOneByParams(wrapper)!=null) {
//                        lastLocation.setUpdateTime(new Date());
//                    }else {
//                        lastLocation.setCreateTime(new Date());
//                    }
//                    lastLocationService.saveLastLocation(lastLocation);
//                }
                return pushData;
            case "OFFUP"://关机上报
            case "AL_BATTERY"://低电量
                pushData.setSendType(2);
                return pushData;
            case "AL"://SOS
                //添加推送省中台信息
                //todo 推送省中台相关
//                saveStudentLiveness(studentCard, "sosqz", "SOS求助", "");
                locationInfo.setExceptionMsg(MessageEnum.SOS.getDesc());
                pushData.setSendType(2);
                sosInfoService.saveSosInfoFromLocationInfo(locationInfo);//存 sos类型 数据 到 sos_info表
                return pushData;
            case "UD"://定位
                //添加推送省中台信息 一日一条
//                String key = studentCard.getImei() + "_gjdw";
//                Long l = (Long) redisService.get(key, Long.class);
//                if (null == l) {
//                    int i = saveStudentLiveness(studentCard, "gjdw", "轨迹定位", "");
//                    if (i > 0) {
//                        redisService.set(key, DateUtil.getTomorrowZeroSeconds(), DateUtil.getTomorrowZeroSeconds());
//                    }
//                }
                pushData.setTerminalUnit(terminalUnit);
                setSafetyInfo(locationInfo, terminalUnit,personId);
                pushData = handleSecurityArea(locationInfo, terminalUnit, pushData);
                if (pushData.getUdMsgType() != null) {
                    pushData.setSendType(2);
                }
                return pushData;
                /*case "FACTORY"://恢复出厂设置
                studentCardService.factoryStudentCard(stuId);
                return null;*/
            case "LOGIN": //开机下发模板消息
                pushData.setTerminalUnit(terminalUnit);
                if ("ICCID".equals(pushData.getTypeIdent())){
                    pushData.setSendType(2);
                }
                return pushData;
            default:
                return pushData;
        }

    }

    //晓羊智教平台推送处理
    private LocationInfo handleXYZJ(String type, TerminalUnit terminalUnit, DalData dalData, LocationInfo locationInfo) throws Exception {
        // 推送iccid
        if ("LOGIN".equals(type)) {//开机
            JSONObject jo = new JSONObject();
            jo.put("DEVICENUM", dalData.getImei());
            jo.put("ICCID", dalData.getIccid());
            sendDalHandle(XiaoYangUrlConst.PUSH_DEV_ICCID, jo);
            return null;
        }
        //短信状态
        if ("SMSMSGSTA".equals(type)) {
            JSONObject jo = new JSONObject();
            jo.put("DEVICENUM", dalData.getImei());
            jo.put("SMSUID", dalData.getSmsUid());
            jo.put("STATUS", dalData.getStatus());
            sendDalHandle(XiaoYangUrlConst.PUSH_DEV_SMS_STATUS, jo);
            return null;
        }
        if ("FACTORY".equals(type)) {//恢复出厂不处理
            return null;
        }
        //sos报警
        if ("AL".equals(type)) {
            //添加推送省中台信息
            //todo 推送省中台相关
//            saveStudentLiveness(studentCard, "sosqz", "SOS求助", "");
            locationInfo.setExceptionMsg(MessageEnum.SOS.getDesc());
            JSONObject jo = dalData2Jo(dalData);
            sendDalHandle(XiaoYangUrlConst.PUSH_DEVICE_SOS, jo);
            return locationInfo;
        }
        String address = getAddress(dalData.getLongitude(), dalData.getLatitude(), null);
        locationInfo.setAddress(address);
        //定位
        if ("UD".equals(type)) {
            //添加推送省中台信息 一日一条
            String key = terminalUnit.getCardNum() + "_gjdw";
            Long l = (Long) redisService.get(key, Long.class);
            if (null == l) {
                //todo 推送省中台相关
//                int i = saveStudentLiveness(terminalUnit, "gjdw", "轨迹定位", "");
//                if (i > 0) {
//                    redisService.set(key, DateUtil.getTomorrowZeroSeconds(), DateUtil.getTomorrowZeroSeconds());
//                }
            }
            if (StringUtils.isBlank(address)) {
                log.info("UD:{} 地址为空，不处理", locationInfo.getMsgId());
                return null;
            }
            JSONObject jo = dalData2Jo(dalData);
            jo.put("POSDESC", address);
            jo.put("ISONLINE", 1);
            sendDalHandle(XiaoYangUrlConst.PUSH_DEVICE_CURPOS, jo);
            // 进出围栏
            setFenceInfo(locationInfo);
            AsyncExecuteHandleFenceArea(terminalUnit, dalData, locationInfo);

            // 推送步数
            //handleStep(dalData);
            return locationInfo;
        }
        // 低电量
        if ("AL_BATTERY".equals(type)) {
            JSONObject jo = dalData2Jo(dalData);
            jo.put("POSDESC", address);
            jo.put("ISONLINE", 1);
            sendDalHandle(XiaoYangUrlConst.PUSH_DEVICE_LOWBAT, jo);
            return locationInfo;
        }
        return null;
    }

    //    翼智慧云教平台推送处理
    private LocationInfo handleYZH(String type, TerminalUnit terminalUnit, DalData dalData, LocationInfo locationInfo) {
        //定位
        if ("UD".equals(type)) {
            //添加推送省中台信息 一日一条
            String key = terminalUnit.getCardNum() + "_gjdw";
            Long l = (Long) redisService.get(key, Long.class);
            if (null == l) {
                //todo 推送省中台相关
//                int i = saveStudentLiveness(terminalUnit, "gjdw", "轨迹定位", "");
//                if (i > 0) {
//                    redisService.set(key, DateUtil.getTomorrowZeroSeconds(), DateUtil.getTomorrowZeroSeconds());
//                }
            }
            String address = getAddress(dalData.getLongitude(), dalData.getLatitude(), null);
            locationInfo.setAddress(address);
            if (StringUtils.isBlank(address)) {
                log.info("UD:{} 地址为空，不处理", locationInfo.getMsgId());
                return null;
            }
            JSONObject jo = dalData3Jo(dalData);
//            sendYZHHandle("yzh/locationReport", jo);
            sendYZHHandle("weixinkdxgimeicallback.php", jo);
            log.info(" 翼智慧云教平台推送数据:", jo.toJSONString());
            // 进出围栏
//            try {
//                setFenceInfo(locationInfo);
//                handleFenceArea(dalData, locationInfo);
//            } catch (Exception e) {
//                log.error("", e);
//            }
            return locationInfo;
        }
        //type:2 sos报警
        if ("AL".equals(type)) {
            //添加推送省中台信息
            //todo 推送省中台相关
//            saveStudentLiveness(studentCard, "sosqz", "SOS求助", "");
            locationInfo.setExceptionMsg(MessageEnum.SOS.getDesc());
            JSONObject jo = new JSONObject();
            jo.put("electricity", dalData.getPower());
            jo.put("type", 2);
            jo.put("imei", dalData.getImei());
            jo.put("dataTime ", DateUtil.convert2String(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
            sendYZHHandle("weixinkdxgalarmcallback.php", jo);
//            sendYZHHandle("yzh/alarmReport", jo);
            return locationInfo;
        }
        // type: 1低电量
        if ("AL_BATTERY".equals(type)) {
            JSONObject jo = new JSONObject();
            jo.put("electricity", dalData.getPower());
            jo.put("type", 1);
            jo.put("imei", dalData.getImei());
            jo.put("dataTime ", DateUtil.convert2String(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
//            sendYZHHandle("yzh/alarmReport", jo);
            sendYZHHandle("weixinkdxgalarmcallback.php", jo);
            return locationInfo;
        }
        return null;
    }

    //    紫光翼智慧平台推送处理
    private LocationInfo handleZGYZH(String type, TerminalUnit terminalUnit, DalData dalData, LocationInfo locationInfo) {
        log.info("紫光推送定位入参:,type{},studentCard{},dalData{},locationInfo{}", type, terminalUnit, dalData, locationInfo);
        if ("UD".equals(type)) {
            //添加推送省中台信息 一日一条
            String key = terminalUnit.getCardNum() + "_gjdw";
            Long l = (Long) redisService.get(key, Long.class);
            if (null == l) {
                //todo 推送省中台相关
//                int i = saveStudentLiveness(studentCard, "gjdw", "轨迹定位", "");
//                if (i > 0) {
//                    redisService.set(key, DateUtil.getTomorrowZeroSeconds(), DateUtil.getTomorrowZeroSeconds());
//                }
            }
            String address = getAddress(dalData.getLongitude(), dalData.getLatitude(), null);
            log.info("调用高德地图转换地址，imei：{}，Longitude：{}，Latitude:{},address:{}", dalData.getImei(), locationInfo.getLon(), locationInfo.getLat(), address);
            locationInfo.setAddress(address);
            if (StringUtils.isBlank(address)) {
                log.info("UD:{} 地址为空，不处理", locationInfo.getMsgId());
                return null;
            }
            JSONObject jo = new JSONObject();
            jo.put("imei", dalData.getImei());
            jo.put("battery", dalData.getPower());
            jo.put("address", address);
            jo.put("latitude", dalData.getLatitude());
            jo.put("longitude", dalData.getLongitude());
            jo.put("step", dalData.getSteps());
            jo.put("dataTime ", DateUtil.convert2String(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
            sendZGYZHHandle("https://web.wiscloudchina.com/api/electronic/KDC/callback", jo);
            log.info(" 紫光翼智慧平台推送数据:{}", jo.toJSONString());
            return locationInfo;
        }
        return null;
    }

    //福建电信云助手
    private LocationInfo handleFJDXYZS(String type, TerminalUnit terminalUnit, DalData dalData, LocationInfo locationInfo) {
        JSONObject jo = new JSONObject();
        String randomStr = UUIDUtil.uuid();
        String time = DateUtil.getNowDateWholePoint("yyyyMMddHHmmss");
        String sign = FJSignUtils.getSign(randomStr, time);
        String reportTime = DateUtil.convert2String(locationInfo.getUploadTime().getTime(), "yyyyMMddHHmmss");
        jo.put("appId", FJSignUtils.appId);
        jo.put("time", time);
        jo.put("randomStr", randomStr);
        jo.put("sign", sign);
        String imeiAES = AESUtils.enCode(terminalUnit.getCardNum(), FJSignUtils.appKey);
        jo.put("imei", imeiAES);
        jo.put("reportTime", reportTime);
        log.info("福建电信云助手平台接收并推送数据：{}", dalData);
        if ("UD".equals(type)) { //定位上报 加围栏上报
            //添加推送省中台信息 一日一条
            String key = terminalUnit.getCardNum() + "_gjdw";
            Long l = (Long) redisService.get(key, Long.class);
            if (null == l) {
                //todo 推送省中台相关
//                int i = saveStudentLiveness(studentCard, "gjdw", "轨迹定位", "");
//                if (i > 0) {
//                    redisService.set(key, DateUtil.getTomorrowZeroSeconds(), DateUtil.getTomorrowZeroSeconds());
//                }
            }
            jo.put("lng", locationInfo.getLon());
            jo.put("lat", locationInfo.getLat());
            String address = locationInfo.getAddress();
            address = getAddress(locationInfo.getLon(), locationInfo.getLat(), address);
            if (StringUtils.isBlank(address)) {
                address = "未知";
            }
            jo.put("position", address);
            jo.put("pushType", "0");
            sendFJDXYHandle("/msgPush/positionReport", jo);
            setSafetyInfo(locationInfo, terminalUnit,personId);
            try {
                jo.remove("pushType");
                String mac = locationInfo.getMac();
                String mode = "2";
                if ("GPS".equals(mac)) {
                    mode = "3";
                } else if ("WIFI".equals(mac)) {
                    mode = "1";
                }
                jo.put("mode", mode);
                AsyncHandleSecurityAreaFJDXY(locationInfo, terminalUnit, jo);
            } catch (Exception e) {
                log.error("dal handleXXT error", e);
            }
        } else if ("AL".equals(type)) { //sos上报
            //添加推送省中台信息
            //todo 推送省中台相关
//            saveStudentLiveness(studentCard, "sosqz", "SOS求助", "");
            locationInfo.setExceptionMsg(MessageEnum.SOS.getDesc());
            jo.put("lng", locationInfo.getLon());
            jo.put("lat", locationInfo.getLat());
            String address = locationInfo.getAddress();
            address = getAddress(locationInfo.getLon(), locationInfo.getLat(), address);
            if (StringUtils.isBlank(address)) {
                address = "未知";
            }
            jo.put("position", address);
            sendFJDXYHandle("/msgPush/sosReport", jo);
        } else if ("AL_BATTERY".equals(type)) { //低电量上报
            jo.put("battery", locationInfo.getElectricity());
            sendFJDXYHandle("/msgPush/batteryReport", jo);
        }
        return locationInfo;
    }

    //壹教云,辽宁联通,天立教育
    private LocationInfo handleYJY(String type, TerminalUnit terminalUnit, DalData dalData, LocationInfo locationInfo) {
        log.info("壹教云推送定位入参:,type{},studentCard{},dalData{},locationInfo{}", type, terminalUnit, dalData, locationInfo);
        if ("UD".equals(type)) {
            //添加推送省中台信息 一日一条
            String key = terminalUnit.getCardNum() + "_gjdw";
            Long l = (Long) redisService.get(key, Long.class);
            if (null == l) {
                //todo 推送省中台相关
//                int i = saveStudentLiveness(studentCard, "gjdw", "轨迹定位", "");
//                if (i > 0) {
//                    redisService.set(key, DateUtil.getTomorrowZeroSeconds(), DateUtil.getTomorrowZeroSeconds());
//                }
            }
            String address = getAddress(dalData.getLongitude(), dalData.getLatitude(), null);
            log.info("调用高德地图转换地址，imei：{}，Longitude：{}，Latitude:{},address:{}", dalData.getImei(), locationInfo.getLon(), locationInfo.getLat(), address);
            locationInfo.setAddress(address);
            if (StringUtils.isBlank(address)) {
                log.info("UD:{} 地址为空，不处理", locationInfo.getMsgId());
                return null;
            }
            JSONObject jo = new JSONObject();
            jo.put("imei", dalData.getImei());
            jo.put("battery", dalData.getPower());
            jo.put("address", address);
            jo.put("latitude", dalData.getLatitude());
            jo.put("longitude", dalData.getLongitude());
            jo.put("step", dalData.getSteps());
            jo.put("dataTime", DateUtil.convert2String(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
//            String uploadType = dalData.getUploadType();
            String uploadType = dalData.getType();
            Integer locationType = 0;
            log.info("定位类型111111111111111：{}", uploadType);
            if (StringUtils.isNotEmpty(uploadType)) {
                switch (uploadType) {
                    case "GPS":
                        locationType = 1;
                        break;
                    case "BASE":
                        locationType = 2;
                        break;
                    case "WIFI":
                        locationType = 3;
                        break;
                }
            }
            jo.put("locationType", locationType);
            if (CommonResource.CARDVERSION_YJY.equals(terminalUnit.getDistributionChannel())){
                sendYJYHandle("/actionLogCollect", jo);
                log.info("壹教云推送数据:{}", jo.toJSONString());
            }else if (CommonResource.CARDVERSION_LNLT.equals(terminalUnit.getDistributionChannel())){
                sendLNLTHandle("/positionKeDao", jo);
                log.info("辽宁联通推送数据:{}", jo.toJSONString());
            }else if (CommonResource.CARDVERSION_TLJY.equals(terminalUnit.getDistributionChannel())){
                sendTLJYHandle("", jo);
                log.info("天立教育推送数据:{}", jo.toJSONString());
            }
            return locationInfo;
        }
        JSONObject jo = new JSONObject();
        jo.put("imei", terminalUnit.getCardNum());
        if ("AL".equals(type)) { //sos上报
            //添加推送省中台信息
            //todo 推送省中台相关
//            saveStudentLiveness(studentCard, "sosqz", "SOS求助", "");
            locationInfo.setExceptionMsg(MessageEnum.SOS.getDesc());
            jo.put("longitude", locationInfo.getLon());
            jo.put("latitude", locationInfo.getLat());
            jo.put("messageType", "2");
            jo.put("electricity", "");
            String address = locationInfo.getAddress();
            address = getAddress(locationInfo.getLon(), locationInfo.getLat(), address);
            if (StringUtils.isBlank(address)) {
                address = "未知";
            }
            jo.put("address", address);
            if (CommonResource.CARDVERSION_YJY.equals(terminalUnit.getDistributionChannel())){
                sendYJYHandle("/remindMessage", jo);
                log.info("壹教云推送数据:{}", jo.toJSONString());
            }else if (CommonResource.CARDVERSION_LNLT.equals(terminalUnit.getDistributionChannel())){
                sendLNLTHandle("", jo);
                log.info("辽宁联通推送数据:{}", jo.toJSONString());
            }else if (CommonResource.CARDVERSION_TLJY.equals(terminalUnit.getDistributionChannel())){
                sendTLJYHandle("", jo);
                log.info("天立教育推送数据:{}", jo.toJSONString());
            }
        } else if ("AL_BATTERY".equals(type)) { //低电量上报
            jo.put("messageType", "1");
            jo.put("longitude", "");
            jo.put("latitude", "");
            jo.put("address", "");
            jo.put("electricity", locationInfo.getElectricity());
            if (CommonResource.CARDVERSION_YJY.equals(terminalUnit.getDistributionChannel())){
                sendYJYHandle("/remindMessage", jo);
                log.info("壹教云推送数据:{}", jo.toJSONString());
            }else if (CommonResource.CARDVERSION_LNLT.equals(terminalUnit.getDistributionChannel())){
                sendLNLTHandle("", jo);
                log.info("辽宁联通推送数据:{}", jo.toJSONString());
            }else if (CommonResource.CARDVERSION_TLJY.equals(terminalUnit.getDistributionChannel())){
                sendTLJYHandle("", jo);
                log.info("天立教育推送数据:{}", jo.toJSONString());
            }
        }
        if ("HEARTBEAT".equals(type)) {
            jo.put("electricity", locationInfo.getElectricity());
            if (StringUtils.isEmpty(locationInfo.getStep())) {
                jo.put("step", "");
            } else {
                jo.put("step", locationInfo.getStep());
            }
            jo.put("time", DateUtil.convert2String(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
            if (StringUtils.isEmpty(dalData.getLocateReportRate())) {
                jo.put("locationUpload", "");
            } else {
                jo.put("locationUpload", dalData.getLocateReportRate());
            }
            if (StringUtils.isEmpty(dalData.getSignalStrength())) {
                jo.put("signalIntensity", "");
            } else {
                jo.put("signalIntensity", dalData.getSignalStrength());
            }
            if (StringUtils.isEmpty(dalData.getNetStatus())) {
                jo.put("networkStatus", "");
            } else {
                jo.put("networkStatus", dalData.getNetStatus());
            }
            if (CommonResource.CARDVERSION_YJY.equals(terminalUnit.getDistributionChannel())){
                sendYJYHandle("/lastIotAction", jo);
                log.info("壹教云推送数据:{}", jo.toJSONString());
            }else if (CommonResource.CARDVERSION_LNLT.equals(terminalUnit.getDistributionChannel())){
                sendLNLTHandle("", jo);
                log.info("辽宁联通推送数据:{}", jo.toJSONString());
            }else if (CommonResource.CARDVERSION_TLJY.equals(terminalUnit.getDistributionChannel())){
                sendTLJYHandle("", jo);
                log.info("天立教育推送数据:{}", jo.toJSONString());
            }
        }
        if ("CALLRECORD".equals(type)){
            jo.put("callPhone", dalData.getCallNum());
            jo.put("callType", dalData.getCallType());
            jo.put("callTime", dalData.getCallStart());
            jo.put("callDuration",dalData.getCallTime() );

            log.info("第三方通话记录入参-->{}",jo);
            if (CommonResource.CARDVERSION_YJY.equals(terminalUnit.getDistributionChannel())){
                sendYJYHandle("/getCallRecord", jo);
                log.info("壹教云推送数据:{}", jo.toJSONString());
            }else if (CommonResource.CARDVERSION_LNLT.equals(terminalUnit.getDistributionChannel())){
                sendLNLTHandle("", jo);
                log.info("辽宁联通推送数据:{}", jo.toJSONString());
            }else if (CommonResource.CARDVERSION_TLJY.equals(terminalUnit.getDistributionChannel())){
                sendTLJYHandle("", jo);
                log.info("天立教育推送数据:{}", jo.toJSONString());
            }
        }
        if("MSGLOG".equals(type)) {//短信转发上报回调
            /**
             * 壹教云：短信代收
             */
            StudentCard studentCardByImei = studentCardService.getStudentCardByImei(c40DataVO.getImei());
            String cardVersion = studentCardByImei.getCardVersion();
            if ("YJY".equals(cardVersion)) {
                //推送给壹教云
                String msgContent = c40DataVO.getShortMsg();
                if(StringUtils.isNotBlank(msgContent)) {
                    msgContent = UnicodeUtil.unicodeToStrings(msgContent);
                }
//                JSONObject jo = new JSONObject();
                jo.put("imei", terminalUnit.getCardNum());
                jo.put("phone", c40DataVO.getOtherCallNum());
                jo.put("smsContent", msgContent);
                jo.put("smsTime", c40DataVO.getReceivedTime());
                log.info("壹教云短信代收入参-->{}",jo);
                //url
                String url = TrdUrlUtil.YJY_URL + "/getSmsRecord";
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/json");

                ContentType contentType = ContentType.APPLICATION_JSON;
                ResultConfig<String> result = httpService.doStringEntityPost(url, headers,jo.toString() , contentType,"utf-8");
                log.info("壹教云短信代收{} 返回:{}", jo.getString("url"), result);

            }
        }
        JSONObject replyJo = new JSONObject();
        replyJo.put("imei", dalData.getImei());
        int commandType = 6;
        if ("PHL".equals(type) || "SOS1".equals(type)  || "REMIND".equals(type) || "SILENCETIME1".equals(type) || "SMSMSG".equals(type)){
            switch (type){
                case "PHL" :
                    commandType = 1;
                    break;
                case "SOS1" :
                    commandType = 2;
                    break;
                case "REMIND" :
                    commandType = 3;
                    break;
                case "SILENCETIME1" :
                    commandType = 4;
                    break;
                case "SMSMSG" :
                    commandType = 5;
                    break;
            }
            replyJo.put("commandType", commandType);
            if (commandType == 5){
                if (!StuCardTypeEnum.XTC40.getType().equals(terminalUnit.getTerminalSeries())){
                    return locationInfo;
                }
            }
            UniversalReply universalReply = super.getUniversalReply(dalData.getImei(), commandType, terminalUnit.getDistributionChannel());
            if (null == universalReply){
                return locationInfo;
            }
            log.info("回复指令发送数据:universalReply{}",universalReply);
            replyJo.put("tagId", universalReply.getTagId());
            Boolean result = super.updateUniversalReply(universalReply.getId());
            log.info("回复指令发送数据:imei{},type{},result{}",dalData.getImei(),type,result);
            if (CommonResource.CARDVERSION_YJY.equals(terminalUnit.getDistributionChannel())){
                sendYJYHandle("/commandReply", replyJo);
                log.info("壹教云推送数据:{}", replyJo.toJSONString());
            }else if (CommonResource.CARDVERSION_LNLT.equals(terminalUnit.getDistributionChannel())){
                sendLNLTHandle("", replyJo);
                log.info("辽宁联通推送数据:{}", replyJo.toJSONString());
            }else if (CommonResource.CARDVERSION_TLJY.equals(terminalUnit.getDistributionChannel())){
                sendTLJYHandle("", replyJo);
                log.info("天立教育推送数据:{}", replyJo.toJSONString());
            }
        } else if ("SMSMSGSTA".equals(type)){
            if (!StuCardTypeEnum.XTC40.getType().equals(terminalUnit.getTerminalSeries())){
                return locationInfo;
            }
            replyJo.put("tagId", dalData.getSmsUid());
            replyJo.put("commandType", commandType);
            log.info("壹教云消息已阅发送数据:imei{},type{}",dalData.getImei(),type);
            if (CommonResource.CARDVERSION_YJY.equals(terminalUnit.getDistributionChannel())){
                sendYJYHandle("/commandReply", replyJo);
                log.info("壹教云推送数据:{}", replyJo.toJSONString());
            }else if (CommonResource.CARDVERSION_LNLT.equals(terminalUnit.getDistributionChannel())){
                sendLNLTHandle("", replyJo);
                log.info("辽宁联通推送数据:{}", replyJo.toJSONString());
            }else if (CommonResource.CARDVERSION_TLJY.equals(terminalUnit.getDistributionChannel())){
                sendTLJYHandle("", replyJo);
                log.info("天立教育推送数据:{}", replyJo.toJSONString());
            }
        }
        return locationInfo;
    }

    //    翼智慧上海百学平台推送处理
    private LocationInfo handleSHBX(String type, TerminalUnit terminalUnit, DalData dalData, LocationInfo locationInfo) {
        //定位
        if ("UD".equals(type)) {
            //添加推送省中台信息 一日一条
            String key = terminalUnit.getCardNum() + "_gjdw";
            Long l = (Long) redisService.get(key, Long.class);
            if (null == l) {
                //todo 推送省中台相关
//                int i = saveStudentLiveness(studentCard, "gjdw", "轨迹定位", "");
//                if (i > 0) {
//                    redisService.set(key, DateUtil.getTomorrowZeroSeconds(), DateUtil.getTomorrowZeroSeconds());
//                }
            }
            String address = getAddress(dalData.getLongitude(), dalData.getLatitude(), null);
            locationInfo.setAddress(address);
            if (StringUtils.isBlank(address)) {
                log.info("UD:{} 地址为空，不处理", locationInfo.getMsgId());
                return null;
            }
            JSONObject jo = dalData3Jo(dalData);
            sendSHBXHandle("weixinkdxgimeicallback.php", jo);
//            sendSHBXHandle("bx/locationReport", jo);
            log.info(" 翼智慧云上海百学平台推送数据:", jo.toJSONString());
            // 进出围栏
//            try {
//                setFenceInfo(locationInfo);
//                handleFenceArea(dalData, locationInfo);
//            } catch (Exception e) {
//                log.error("", e);
//            }
            return locationInfo;
        }
        //type:2 sos报警
        if ("AL".equals(type)) {
            //添加推送省中台信息
            //todo 推送省中台相关
//            saveStudentLiveness(studentCard, "sosqz", "SOS求助", "");
            locationInfo.setExceptionMsg(MessageEnum.SOS.getDesc());
            JSONObject jo = new JSONObject();
            jo.put("electricity", dalData.getPower());
            jo.put("type", 2);
            jo.put("imei", dalData.getImei());
            jo.put("dataTime ", DateUtil.convert2String(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
//            sendSHBXHandle("bx/alarmReport", jo);
            sendSHBXHandle("weixinkdxgalarmcallback.php", jo);
            return locationInfo;
        }
        // type: 1低电量
        if ("AL_BATTERY".equals(type)) {
            JSONObject jo = new JSONObject();
            jo.put("electricity", dalData.getPower());
            jo.put("type", 1);
            jo.put("imei", dalData.getImei());
            jo.put("dataTime ", DateUtil.convert2String(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
//            sendSHBXHandle("bx/alarmReport", jo);
            sendSHBXHandle("weixinkdxgalarmcallback.php", jo);
            return locationInfo;
        }
        return null;
    }

    //校芯通平台处理
    private LocationInfo handleSxlXXT(String type, TerminalUnit terminalUnit, LocationInfo locationInfo,PushData pushData) throws Exception {
        String stuId = terminalUnit.getCardNum();
        String lat = locationInfo.getLat(), lng = locationInfo.getLon(), address = locationInfo.getAddress();
        try {
            switch (type) {
                case "AL_SOS"://SOS
                    //添加推送省中台信息
                    //saveStudentLiveness(studentCard, "sosqz", "SOS求助", "");
                    locationInfo.setExceptionMsg(MessageEnum.SOS.getDesc());
                    //trajectoryClient.setMessage(studentCard, localtionInfo.getUploadTime(), lat, lng, MessageEnum.SOS.getType(), localtionInfo.getElectricity(), address, localtionInfo.getMac());
                    //sosInfoService.saveSosInfoFromLocationInfo(localtionInfo);//存 sos类型 数据 到 sos_info表
                    return locationInfo;
                case "UD"://普通定位上报
                    //添加推送省中台信息 一日一条
                    String key = terminalUnit.getCardNum() + "_gjdw";
                    Long l = (Long) redisService.get(key, Long.class);
                    if(null == l){
                        /*int i = saveStudentLiveness(studentCard, "gjdw", "轨迹定位", "");
                        if(i > 0){
                            redisService.set(key, DateUtil.getTomorrowZeroSeconds(), DateUtil.getTomorrowZeroSeconds());
                        }*/
                    }
                    String step = locationInfo.getStep();
                    if ((StringUtils.isBlank(lat) || "0".equals(lat)) && (StringUtils.isBlank(lng) || "0".equals(lng)) && (StringUtils.isBlank(step) || "0".equals(step))) {
                        return null;
                    } else if ((StringUtils.isNotBlank(lat) && !"0".equals(lat)) && (StringUtils.isNotBlank(lng) && !"0".equals(lng))) {
                        setSafetyInfo(locationInfo, terminalUnit, personId);
                        handleSecurityArea(locationInfo, terminalUnit,pushData);
                    }
                    return locationInfo;
                case "AL_BATTERY"://低电量
                    //trajectoryClient.setMessage(studentCard, localtionInfo.getUploadTime(), lat, lng, MessageEnum.LOW_ELECTRICITY.getType(), localtionInfo.getElectricity(), address, localtionInfo.getMac());
                    return locationInfo;
                case "POWER_OFF"://设备关机
                    //trajectoryClient.setMessage(studentCard, localtionInfo.getUploadTime(), lat, lng, MessageEnum.POWER_OFF.getType(), localtionInfo.getElectricity(), address, localtionInfo.getMac());
                    return locationInfo;
                case "S25"://恢复出厂
                    studentCardService.factoryStudentCard(stuId);
                    return null;
                default:
                    return null;
            }
        } catch (Exception e) {
            log.error("sxl handleXXT error", e);
        }
        return null;
    }

    //晓羊智教平台推送处理
    private LocationInfo handleSxlXYZJ(String type, TerminalUnit terminalUnit, DalData dalData, LocationInfo locationInfo) {
        // 推送iccid
        if ("ICCID".equals(type)) {
            JSONObject jo = new JSONObject();
            jo.put("DEVICENUM", dalData.getImei());
            jo.put("ICCID", dalData.getIccid());
            sendDalHandle(XiaoYangUrlConst.PUSH_DEV_ICCID, jo);
            return null;
        }
        String address = getSxlAddress(dalData.getLongitude(), dalData.getLatitude());
        locationInfo.setAddress(address);
        //sos报警
        if ("AL_SOS".equals(type)) {
            //添加推送省中台信息
            //saveStudentLiveness(studentCard, "sosqz", "SOS求助", "");
            locationInfo.setExceptionMsg(MessageEnum.SOS.getDesc());
            JSONObject jo = dalData2Jo(dalData);
            jo.put("POSDESC", address);
            sendDalHandle(XiaoYangUrlConst.PUSH_DEVICE_SOS, jo);
            return locationInfo;
        }
        //定位
        if ("UD".equals(type)) {
            //添加推送省中台信息 一日一条
            String key = dalData.getImei() + "_gjdw";
            Long l = (Long) redisService.get(key, Long.class);
            if(null == l){
                /*int i = saveStudentLiveness(studentCard, "gjdw", "轨迹定位", "");
                if(i > 0){
                    redisService.set(key, DateUtil.getTomorrowZeroSeconds(), DateUtil.getTomorrowZeroSeconds());
                }*/
            }
            if(StringUtils.isBlank(address)){
                log.info("UD:{} 地址为空，不处理",locationInfo);
                return null;
            }
            JSONObject jo = dalData2Jo(dalData);
            jo.put("POSDESC", address);
            jo.put("ISONLINE", 1);
            sendDalHandle(XiaoYangUrlConst.PUSH_DEVICE_CURPOS, jo);
            // 进出围栏
            try {
                setFenceInfo(locationInfo);
                handleFenceArea(terminalUnit, dalData, locationInfo);
            } catch (Exception e) {
                log.error("", e);
            }
            return locationInfo;
        }
        // 低电量
        if ("AL_BATTERY".equals(type)) {
            JSONObject jo = dalData2Jo(dalData);
            jo.put("POSDESC", address);
            sendDalHandle(XiaoYangUrlConst.PUSH_DEVICE_LOWBAT, jo);
            return locationInfo;
        }
        return null;
    }

    private JSONObject dalData2Jo(DalData dalData) {
        JSONObject jo = new JSONObject();
        jo.put("DEVICENUM", dalData.getImei());
        jo.put("LO", dalData.getLongitude());
        jo.put("LA", dalData.getLatitude());
        String locTime = DateUtil.convert2String(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
        jo.put("LOCTIME", locTime);
        jo.put("BAT", dalData.getPower());
        jo.put("GSM", dalData.getGsmSignalStrength());
        jo.put("GPS", dalData.getSatelliteSize());
//        jo.put("TYPE", dalData.getUploadType());
        String uploadType = dalData.getType();
        return jo;
    }

    private JSONObject dalData3Jo(DalData dalData) {
        JSONObject jo = new JSONObject();
        jo.put("altitude", Double.valueOf(0));
        jo.put("gaodeLatitude", Double.valueOf(dalData.getLatitude()));
        jo.put("gaodeLongitude", Double.valueOf(dalData.getLongitude()));
//        String uploadType = dalData.getUploadType();
        String uploadType = dalData.getType();
        Integer locationType = 0;
        log.info("定位类型111111111111111：", uploadType);
        if (StringUtils.isNotEmpty(uploadType)) {
            switch (uploadType) {
                case "GPS":
                    locationType = 1;
                    break;
                case "BASE":
                    locationType = 2;
                    break;
                case "WIFI":
                    locationType = 3;
                    break;
            }
        }
        jo.put("locationType", locationType);
        String locTime = DateUtil.convert2String(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
        jo.put("dataTime", locTime);
        jo.put("step", dalData.getSteps());
        jo.put("electricity", dalData.getPower());
        jo.put("imei", dalData.getImei());
        return jo;
    }

    private void handleStep(DalData dalData) {
        // 步数
        JSONObject stepJo = new JSONObject();
        stepJo.put("DEVICENUM", dalData.getImei());
        stepJo.put("STEPS", dalData.getSteps());
        stepJo.put("TIME", System.currentTimeMillis());
        sendDalHandle(XiaoYangUrlConst.PUSH_DEVICE_STEP, stepJo);
    }

    private LocationInfo getLocation(LocationInfo locationInfo, DalData dalData) throws InvocationTargetException, IllegalAccessException {

        if (null == locationInfo) {
            log.info("locationInfo null...");
            locationInfo = new LocationInfo();
        }
        String type = dalData.getType();
        //先复制共有字段
        BeanUtils.copyProperties(locationInfo,dalData);
        log.info("copyProperties-dalData: {}",dalData);
        log.info("copyProperties-locationInfo: {}",locationInfo);
        if (StringUtils.isNotBlank(locationInfo.getTypeIdent()) && "HEARTBEAT".equals(locationInfo.getTypeIdent())) {
            //设置驻网状态
            locationInfo.setNetStatus(dalData.getNetStatus());
        }
//        if (StringUtils.isNotBlank(dalData.getStamp())) {
//            long uploadTime = DateUtil.dateToStamp(dalData.getStamp());
//            locationInfo.setUploadTime(uploadTime);
//            locationInfo.setStamp(uploadTime / 1000 + "");
//        }else {
//            String substring = locationInfo.getMsgId().substring(4);
//            long uploadDate = Long.parseLong(substring);
//            locationInfo.setUploadTime(uploadDate);
//        }
        locationInfo.setStamp(String.valueOf(locationInfo.getUploadTime().getTime()/1000));
        locationInfo.setPdop(dalData.getPdop());//定位精度
        locationInfo.setLat(dalData.getLatitude());
        locationInfo.setLon(dalData.getLongitude());
        locationInfo.setCreateTime(new Date());
        locationInfo.setWifi(dalData.getMac());
        locationInfo.setElectricity(dalData.getPower());
        locationInfo.setMac(dalData.getUploadType());
        locationInfo.setStep(dalData.getSteps());

        return locationInfo;
    }

    /**
     * 设置进出围栏信息
     */
    private void setFenceInfo(LocationInfo locationInfo) {
        Integer isSafety = locationInfo.getIsSafety();
        String stuId = locationInfo.getImei();
        String personId = personTerminalInfoService.getBindPersonId(stuId);
        log.info("setXyFenceInfo===>{}, isInFence:{}", stuId, isSafety);
        String key = CommonResource.XY_POLYGON_FENCE_LIST + "_" + stuId;
        List<Fence> fenceList = redisService.getList(key, Fence.class);
        if (fenceList == null && fenceList.isEmpty()){
            log.info("get xyFenceList from businessClient {}", stuId);
            fenceList = fenceService.getFenceByPersonId(personId);
            redisService.set(key,fenceList);
        }
        if (fenceList != null || !fenceList.isEmpty()) {
            for (Fence fence : fenceList) {
                // 1 在围栏内
                // 0 在围栏外
                int inFence = RangeCompareUtil.calculatePoint(locationInfo.getLon(), locationInfo.getLat(), fence.getPolygonList());
                if (1 == inFence) {
                    locationInfo.setIsSafety(inFence);
                    locationInfo.setFenceId(fence.getId());
                    locationInfo.setExceptionMsg("在" + fence.getFenceName() + "(小羊)附近");
                    return;
                }
            }
        }
        locationInfo.setIsSafety(0);
    }

    void AsyncExecuteHandleFenceArea(TerminalUnit terminalUnit, DalData dalData, LocationInfo locationInfo) {
        log.info("AsyncExecuteHandleFenceArea线程创建成功，即将执行任务");
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        CompletableFuture.supplyAsync(new Supplier<Void>() {
            @Override
            public Void get() {
                try {
                    handleFenceArea(terminalUnit,dalData,locationInfo);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return null;
            }
        }, executorService);
        log.info("AsyncExecuteHandleFenceArea线程执行完成，即将结束线程");
        executorService.shutdown();
        log.info("AsyncExecuteHandleFenceArea线程关闭");
    }

    /**
     * 进出围栏
     */
//    @Async
    void handleFenceArea(TerminalUnit terminalUnit, DalData dalData, LocationInfo locationInfo) throws Exception {
        //查询前一条上报数据
        String studentCardId = locationInfo.getImei();
        String key = CommonResource.PRE_LOCATION_KEY + studentCardId;
        LocationInfo preLocationInfo = (LocationInfo) redisService.get(key, LocationInfo.class);
        if (null == preLocationInfo) {
            long stamp;
            if (StringUtils.isNotBlank(locationInfo.getStamp())) {
                stamp = Long.parseLong(locationInfo.getStamp());
            } else {
                stamp = DateUtil.nowEpochMilli() / 1000;
            }
            preLocationInfo = locationInfoService.getPreLocationInfo(stamp, studentCardId);
        }
        int isSafety = locationInfo.getIsSafety() == null ? 0 : locationInfo.getIsSafety();
        int isSafetyPre = (preLocationInfo == null || preLocationInfo.getIsSafety() == null) ? 0 : preLocationInfo.getIsSafety();
        redisService.set(key, locationInfo);//把当前位置数据设置到缓存

        JSONObject jo = dalData2Jo(dalData);
        jo.put("POSDESC", locationInfo.getAddress());

        if (0 == isSafety && 1 == isSafetyPre) {//离开安全区域提示
            //添加推送省中台信息
            //todo 推送省中台相关
//            saveStudentLiveness(studentCard, "dzwlyj", "电子围栏预警", "");
            log.info("电子围栏");
            jo.put("FENCETYPE", 2);
            jo.put("FENCENID", preLocationInfo.getFenceId());

            sendDalHandle(XiaoYangUrlConst.PUSH_DEVICE_FENCE, jo);
        } else if (1 == isSafety && 0 == isSafetyPre) {//回到安全区域提示
            //添加推送省中台信息
            //todo 推送省中台相关
//            saveStudentLiveness(studentCard, "dzwlyj", "电子围栏预警", "");
            log.info("回到围栏");
            jo.put("FENCETYPE", 1);
            jo.put("FENCENID", locationInfo.getFenceId());
            sendDalHandle(XiaoYangUrlConst.PUSH_DEVICE_FENCE, jo);
        }
    }

    private void sendDalHandle(String url, JSONObject params) {
        JSONObject jo = new JSONObject();
        jo.put("url", url);
        jo.put("params", params);
        log.info("内部发送{} : {}", topic, jo);
        xiaoYangDealController.xiaoYangDeal(jo.toJSONString());
//        kafkaTemplate.send(topic, jo.toJSONString());
    }

    private void sendYZHHandle(String url, JSONObject params) {
        JSONObject jo = new JSONObject();
        jo.put("url", url);
        jo.put("params", params);
        log.info("内部发送{} : {}", topic_yzh, jo);
        yiZiHuiController.yiZiHuiDeal(jo.toJSONString());
//        kafkaTemplate.send(topic_yzh, jo.toJSONString());
    }

    private void sendZGYZHHandle(String url, JSONObject params) {
        JSONObject jo = new JSONObject();
        jo.put("url", url);
        jo.put("params", params);
        log.info("内部发送{} : {}", topic_zgyzh, jo);
        zgyzhController.zgyzhDeal(jo.toJSONString());
//        kafkaTemplate.send(topic_zgyzh, jo.toJSONString());
    }

    private void sendYJYHandle(String url, JSONObject params) {
        JSONObject jo = new JSONObject();
        jo.put("url", url);
        jo.put("params", params);
        log.info("内部发送{} : {}", topic_yjy, jo);
        yjyController.YJYDeal(jo.toJSONString());
//        kafkaTemplate.send(topic_yjy, jo.toJSONString());
    }

    private void sendTLJYHandle(String url, JSONObject params) {
        JSONObject jo = new JSONObject();
        jo.put("url", url);
        jo.put("params", params);
        log.info("内部发送{} : {}", topic_tljy, jo);
        tljyController.TLJYDeal(jo.toJSONString());
//        kafkaTemplate.send(topic_tljy, jo.toJSONString());
    }

    private void sendLNLTHandle(String url, JSONObject params) {
        JSONObject jo = new JSONObject();
        jo.put("url", url);
        jo.put("params", params);
        log.info("内部发送{} : {}", topic_lnlt, jo);
        lnltController.LNLTDeal(jo.toJSONString());
//        kafkaTemplate.send(topic_lnlt, jo.toJSONString());
    }

    private void sendFJDXYHandle(String url, JSONObject params) {
        JSONObject jo = new JSONObject();
        jo.put("url", url);
        jo.put("params", params);
        log.info("内部发送{} : {}", topic_fjdxy, jo);
        fjdxyController.dianXYDeal(jo.toJSONString());
//        kafkaTemplate.send(topic_fjdxy, jo.toJSONString());
    }

    private void sendSHBXHandle(String url, JSONObject params) {
        JSONObject jo = new JSONObject();
        jo.put("url", url);
        jo.put("params", params);
        log.info("内部发送{} : {}", topic_shbx, jo);
        yiZiHuiController.shangHaiBXDeal(jo.toJSONString());
//        kafkaTemplate.send(topic_shbx, jo.toJSONString());
    }

    private String getAddress(String lng, String lat, String address) {
        if (StringUtils.isBlank(address)) {
            if ((StringUtils.isNotBlank(lat) && !"0".equals(lat)) && (StringUtils.isNotBlank(lng) && !"0".equals(lng))) {
                address = GaoDeMapUtil.getAddressByLonLat(lng, lat);
            }
        }
        return address;
    }

    void AsyncHandleSecurityAreaFJDXY(LocationInfo locationInfo, TerminalUnit terminalUnit, JSONObject jo) {
        log.info("AsyncHandleSecurityAreaFJDXY线程创建成功，即将执行任务");
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        CompletableFuture.supplyAsync(new Supplier<Void>() {
            @Override
            public Void get() {
                try {
                    handleSecurityAreaFJDXY(locationInfo, terminalUnit, jo);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return null;
            }
        }, executorService);
        log.info("AsyncHandleSecurityAreaFJDXY线程执行完成，即将结束线程");
        executorService.shutdown();
        log.info("AsyncHandleSecurityAreaFJDXY线程关闭");
    }

    //福建电信云进出安全区域处理
//    @Async
    protected void handleSecurityAreaFJDXY(LocationInfo locationInfo, TerminalUnit terminalUnit, JSONObject jo) throws Exception {
        //查询前一条上报数据
        String studentCardId = terminalUnit.getCardNum();
        log.info("---------安全区域判断{},msgId:{}", studentCardId, locationInfo.getMsgId());
        String key = CommonResource.PRE_LOCATION_KEY + studentCardId;
        LocationInfo preLocationInfo = getPreLocationInfo(locationInfo.getStamp(), studentCardId);
        String lat = locationInfo.getLat(), lng = locationInfo.getLon();
        int isSafety = locationInfo.getIsSafety() == null ? 0 : locationInfo.getIsSafety();
        int isSafetyPre = (preLocationInfo == null || preLocationInfo.getIsSafety() == null) ? 0 : preLocationInfo.getIsSafety();
        if (1 == isSafetyPre && 0 == isSafety) {//离开安全区域提示
            String crkey = CommonResource.PRE_COMMAND_CR + studentCardId;
            log.info("{}判断离开安全区域", studentCardId);
            changeMode(terminalUnit,schoolId, isSafety, false);//模式切换
            //添加推送省中台信息
            //todo 推送省中台相关
//                saveStudentLiveness(studentCard, "dzwlyj", "电子围栏预警", "");
            log.info("{}出围栏校验为true", studentCardId);
            String exceptionMsg = locationInfo.getExceptionMsg();
            if (StringUtils.isBlank(exceptionMsg)) {
                exceptionMsg = preLocationInfo.getExceptionMsg();
                if (StringUtils.isBlank(exceptionMsg)) {
                    exceptionMsg = "离开围栏";
                }
            }
            jo.put("fenceInfo", exceptionMsg);
            jo.put("type", "2");
            sendFJDXYHandle("/msgPush/fenceReport", jo);
//                businessClient.setMessage(studentCard, locationInfo.getUploadTime(), lat, lng, MessageEnum.LEAVE_SECURITY_AREA.getType(), locationInfo.getElectricity(), locationInfo.getAddress());
            redisService.remove(crkey);
        } else if (0 == isSafetyPre && 1 == isSafety) {//回到安全区域提示
            log.info("{}判断回到安全区域", studentCardId);
            changeMode(terminalUnit,schoolId, isSafety, false);//模式切换
            log.info("{}进围栏校验为true", studentCardId);
            //添加推送省中台信息
            //todo 推送省中台相关
//                saveStudentLiveness(studentCard, "dzwlyj", "电子围栏预警", "");
            //sendMessage(locationInfo, MessageEnum.BACKTO_SECURITY_AREA.getType(), studentCard);
            jo.put("fenceInfo", locationInfo.getExceptionMsg());
            jo.put("type", "1");
            sendFJDXYHandle("/msgPush/fenceReport", jo);
//                businessClient.setMessage(studentCard, locationInfo.getUploadTime(), lat, lng, MessageEnum.BACKTO_SECURITY_AREA.getType(), locationInfo.getElectricity(), locationInfo.getAddress());
        } else {
            String preModekey = CommonResource.PRE_COMMAND_MODE + terminalUnit.getCardNum();
            String preMode = (String) redisService.get(preModekey, String.class);
            if (StringUtils.isBlank(preMode)) {
                log.info("安全区域未改变且未缓存模式指令，触发模式切换{}", studentCardId);
                changeMode(terminalUnit,schoolId, isSafety, true);
            }
        }
        redisService.set(key, locationInfo);//把当前位置数据设置到缓存
    }

    //修改下发指令的状态为成功
    private void setIPRStatusByTagId(String tagId,int status) {
//        QueryWrapper<IssuedPermissionRecord> wrapper = new QueryWrapper<>();
//        wrapper.eq("tag_id",tagId);
        IssuedPermissionRecord one = issuedPermissionRecordService.getByTagId(tagId);
        if (one!=null) {
            one.setSendStatus(status);
            one.setUpdateTime(new Date());
            issuedPermissionRecordService.saveIssuedPermissionRecord(one);
            return;
        }
        log.info("tagId未查询到数据");
    }

    private void setRemindMessage(String imei, String remindType, String url, Integer type) {
        StudentCard studentCard = studentCardService.getStudentCardByImei(imei);
        if(studentCard == null) {
            log.info("imei；{}未查询到数据", imei);
            return;
        }
        String name = StringUtils.isBlank(studentCard.getName()) ? imei : studentCard.getName();
        messageService.setRemindMessage(imei, name, System.currentTimeMillis(), type, remindType, url);
    }

    private String getSxlAddress(String lng, String lat) {
        if ((StringUtils.isNotBlank(lat) && !"0".equals(lat)) && (StringUtils.isNotBlank(lng) && !"0".equals(lng))) {
            return GaoDeMapUtil.getAddressByLonLat(lng, lat);
        }
        return "";
    }
}

